// 信息
import { useSelector, useDispatch } from 'react-redux'
import { useEffect, useState } from 'react';
import InformationDiv from "react"
import { use } from 'react';
import { information_getChatList } from '../request/api';
import styles from './information.module.css'
import styles1 from "../component/LT.module.css"
import { Avatar, List, Space, Popup, Button, Image } from 'antd-mobile'
import { size } from 'lodash';
import { AudioOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom';
export default function Information() {
    const nav=useNavigate()
    // 向服务器发送的消息
    const [sendValue, setSendValue] = useState('')
    const userId = JSON.parse(localStorage.getItem("userInformation"))
    const [visibleCloseRight, setVisibleCloseRight] = useState(false)

    // websocket 实例

    const [socket, setSocket] = useState(null);
    // 存放聊天数据的列表
    const [message, setMessage] = useState([]);

    // 渲染聊天人员的列表
    const [chatPersonnel, setChatPersonnel] = useState([])


    // 点击聊天人员列表的人
    const handleClick = (_id) => {
        // console.log(_id);
        nav(`/zinLT?yourId=${_id}`)

    }

    useEffect(() => {
        const Information1 = JSON.parse(localStorage.getItem('userInformation'))
        information_getChatList({ _id: Information1.arr._id }).then(res => {
            console.log("获取到的聊天记录", res.data.ChatList);
            setMessage(res.data.ChatList)
        })
    }, [])

    // 根据聊天记录去修改聊天人员列表
    useEffect(() => {
        const Information1 = JSON.parse(localStorage.getItem('userInformation'))
        message.forEach(i => {
            // 如果当前聊天记录的收件人是自己
            let arr = chatPersonnel
            if (i.recipientId._id == Information1.arr._id) {
                // 查找聊天人员列表里面有没有发件人的id
                let findIndex = chatPersonnel.find(res => res._id == i.senderId._id)
                if (findIndex == undefined) {
                    arr.unshift({
                        _id: i.senderId._id,
                        content: i.content,
                        imgSrc: i.senderId.imgUrl,
                        userName: i.senderId.userName
                    })
                }
            } else {
                // 如果发件人是自己的话
                // 查找当前聊天的收件人在没在聊天人员列表内
                let arr = chatPersonnel
                let findIndex = chatPersonnel.find(res => res._id == i.recipientId._id)
                if (findIndex == undefined) {
                    arr.unshift({
                        _id: i.recipientId._id,
                        content: i.content,
                        imgSrc: i.recipientId.imgUrl,
                        userName: i.recipientId.userName
                    })
                }
            }
            setChatPersonnel(chatPersonnel => [...arr])
        })
        console.log("message发生了变化");

    }, [message])

    // 创建websocket实例
    useEffect(() => {
        const Information1 = JSON.parse(localStorage.getItem('userInformation'))
        const newSocket = new WebSocket(`ws://localhost:3000?userId=${Information1.arr._id}`);
        newSocket.addEventListener("open", () => {
            console.log("WebSocket连接已打开");
        });

        // 接收消息
        newSocket.addEventListener("message", (event) => {
            let arr = message
            // console.log("接收到的数据", JSON.parse(event.data));
            arr.push(JSON.parse(event.data))
            console.log("arr123", arr);
            setMessage(message => [...arr])
        });
        newSocket.addEventListener("close", (e) => {
            console.log(e);
            console.log("WebSocket连接已关闭");
        });
        newSocket.addEventListener("eror", (error) => {
            console.log("WebSocket出错：", error);
        });

        setSocket(newSocket);

        return () => {

            // 组件卸载时关闭WebSocket连接

            if (newSocket) {

                newSocket.close();

            }

        };

    }, []);
    return <>
        <div style={{ paddingLeft: "12.5rem" }}>
            <span style={{ fontSize: "2.0833rem" }}>消息</span>
        </div>
        {
            chatPersonnel.map(i => <div key={i._id} onClick={() => handleClick(i._id)}>
                <div className={styles.userDiv}>
                    <div style={{ margin: "0.4167rem 0.4167rem" }}>

                        <Avatar src={i.imgSrc} style={{ width: "3.3333rem", height: "3.3333rem" }} />
                    </div>
                    <div style={{ paddingTop: "0.8333rem" }}>
                        <span style={{ fontSize: "1.4583rem" }}>{i.userName}:</span>
                        <br />
                        <span>{i.content}</span>
                    </div>
                </div>
                <hr />
            </div >)
        }

    </>
}